<template>
  <div>
    <el-dialog :title="title" :fullscreen=true :close-on-click-modal="false" :visible.sync="visible" @close="OnClose">
      <el-row :gutter="10">
        <el-col :span="15">
          <el-card shadow="never" :body-style="contentViewHeight" class="uni-map-panel">
            <PointAddList ref="pointAddList" :floorId='inputForm.floor.id' type="seat"
              url='/smis/seat/jfSeatList/list' nameKey='name' @onMapClick="onMapClick"
              @onDataClick="onDataClick" @dbClick="doSubmit()"></PointAddList>
          </el-card>
        </el-col>
        <el-col :span="9">
          <el-card shadow="never" :body-style="contentViewHeight" class="uni-data-panel">
            <el-form :model="inputForm" ref="inputForm" v-loading="loading" label-width="120px">
              <el-row :gutter="15">
                <el-col :span="22">
                  <el-form-item label="所属区域" prop="group.id" :rules="[
                        {required: true, message:'所属组不能为空', trigger:'blur'}
                       ]">
                    <SelectTree ref="group" :props="{
                                value: 'id',             // ID字段名
                                label: 'name',         // 显示名称
                                children: 'childNodes'    // 子级字段名
                              }" url="/smis/seat/jfSeatGroup/treeData" :value="inputForm.group.id" :clearable="true"
                      :accordion="true" @getValue="(value) => {inputForm.group.id=value}" />
                  </el-form-item>
                </el-col>
                <el-col :span="22">
                    <el-form-item label="楼层" prop="floor.id"
                      :rules="[
                      {required: true, message:'楼层不能为空', trigger:'blur'}
                    ]">
                  <SelectTree
                    ref="floor"
                    :props="{
                        value: 'id',             // ID字段名
                        label: 'showName',         // 显示名称
                        children: 'childNodes'    // 子级字段名
                      }"
                    url="/smis/floor/jfFloor/treeData"
                    :value="inputForm.floor.id"
                    :clearable="true"
                    :accordion="true"
                    @getValue="(value) => {inputForm.floor.id=value; resetFields(); $refs.pointAddList.showFloor(value); inputForm.name=''}"/>
                  </el-form-item>
                </el-col>
                <el-col :span="22" :offset="2" style="margin-bottom: 10px;">
                  <el-radio-group v-model="punctuateModel" size="mini">
                    <el-radio-button label="hand">手工标点</el-radio-button>
                    <el-radio-button label="section">分段标点</el-radio-button>
                  </el-radio-group>
                </el-col>
                <el-col :span="22" v-if="punctuateModel === 'hand'">
                  <el-form-item label="座位编号" prop="name" :rules="[
                        {required: true, message:'座位编号不能为空', trigger:'blur'}
                       ]">
                    <el-input v-model="inputForm.name" placeholder="请填写座位编号"></el-input>
                    <el-checkbox v-model="autoUp" style="position: absolute; right: 5px; ">自增</el-checkbox>
                  </el-form-item>
                  <el-col :span="22">
                    <el-form-item label="x" prop="x" :rules="[
                           {required: true, message:'x不能为空', trigger:'blur'}
                          ]">
                      <el-input v-model="inputForm.x" placeholder="请填写x"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="22">
                    <el-form-item label="y" prop="y" :rules="[
                           {required: true, message:'y不能为空', trigger:'blur'}
                          ]">
                      <el-input v-model="inputForm.y" placeholder="请填写y"></el-input>
                    </el-form-item>
                  </el-col>
                </el-col>
                <template v-else-if="punctuateModel === 'section'">
                  <el-col :span="22">
                    <el-form-item label="开始编号" prop="nameStart" :rules="[
                          {required: true, message:'开始编号不能为空', trigger:'blur'}
                         ]">
                      <el-input v-model="inputForm.nameStart" placeholder="请填写开始编号"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="22">
                    <el-form-item label="结束编号" prop="nameEnd" :rules="[
                      {required: true, message:'开始编号不能为空', trigger:'blur'}
                         ]">
                      <el-input v-model="inputForm.nameEnd" placeholder="请填写结束编号"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="22">
                    <div v-for="point in points">{{'['+point.x+','+point.y+']'}}</div>
                    <div style="color: #096DD9;" @click="clearPoints()">清空</div>
                  </el-col>
                </template>
                <el-col :span="22">
                   <el-form-item label="z" prop="z"
                       :rules="[
                         {required: true, message:'z不能为空', trigger:'blur'}
                        ]">
                     <el-input v-model="inputForm.z" placeholder="请填写z"     ></el-input>
                  </el-form-item>
               </el-col>
                <!-- <el-col :span="12">
                   <el-form-item label="地图模型" prop="meshName"
                       :rules="[
                        ]">
                     <el-input v-model="inputForm.meshName" placeholder="请填写地图模型"     ></el-input>
                  </el-form-item>
               </el-col> -->
              </el-row>
            </el-form>
            <el-button type="primary" @click="doSubmit()" v-noMoreClick>添加</el-button>

            <div class="uni-addlist-delete" v-if="selectItem.id !== ''">
              <div>当前选中了{{selectItem.name}}</div>
              <el-button type="danger" size="small" @click="doDelete()" v-noMoreClick>删除</el-button>
            </div>
            <div class="uni-foot">
              <el-button type="text" @click="doUpdate()" v-noMoreClick>更新点位模型名称</el-button>
              <el-popover placement="top" width="240" trigger="hover">
                <div class="uni-popover-notice">可用通过<span>x、y坐标</span>,自动计算并保存<span>模型名称</span></div>
                <i slot="reference" class="el-icon-question" ></i>
              </el-popover>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
  import SelectTree from '@/components/treeSelect/treeSelect.vue'
  import PointAddList from '@/components/jfMap/pointAddList.vue'
  import GridSelect from '@/components/gridSelect'
  export default {
    data() {
      return {
        title: '',
        visible: false,
        loading: false,
        autoUp: false,
        punctuateModel: 'hand', // 标点的方式，手动一个个标点，还是画好线后，分段自动标点
        selectItem: {
          id: '',
          name: ''
        },
        points: [],
        seatPointList: [],   // 分段模式中，计算出每个座椅的位置点
        inputForm: {
          id: '',
          group: {
            id: ''
          },
          name: '',
          meshName: '',
          nameStart: '',
          nameEnd: '',
          type: '',
          sort: '',
          floor: {
            id: ''
          },
          x: '',
          y: '',
		  z: ''
        }
      }
    },
    components: {
      SelectTree,
      PointAddList,
      GridSelect
    },
    computed: {
      contentViewHeight() {
        let height = this.$store.state.common.documentClientHeight - 152
        return {
          height: height + 'px'
        }
      }
    },
    methods: {
      dbClick() {
        console.log("dbClick")
      },
      init(groupId) {
        this.title = `批量添加`
        this.visible = true
        this.loading = false
        this.$nextTick(() => {
          this.resetFields()
          // console.log(groupId)
          this.inputForm.group.id = groupId
          // this.$refs.pointAddList.resize();
        })
      },
      resetFields() {
        this.inputForm.id = ''
        this.inputForm.name = this.autoUp ? this.getAutoUpNumber(this.inputForm.name) : ''
        this.inputForm.meshName = ''
        this.inputForm.x = ''
        this.inputForm.y = ''
		this.inputForm.z = ''
      },
      getAutoUpNumber(code) {
        if (!code || code === "") {
          return ""
        }
        var list = code.split("")
        var numCode = ''
        for (var i = list.length - 1; i >= 0; i--) {
          var isnum = /^\d+$/.test(list[i]);
          if (isnum) {
            numCode = list[i] + numCode
          } else {
            break
          }
        }
        if (numCode === '') {
          return code
        }
        var prefix = code.substr(0, code.length - numCode.length)
        var newCode = (parseInt(numCode) + 1) + ''
        for (var len = newCode.length, i = 0; i < numCode.length - len; i++) {
          newCode = '0' + newCode
        }
        return prefix + newCode
      },
      // 表单提交
      doSubmit() {
        this.$refs['inputForm'].validate((valid) => {
          if (valid) {
            if(this.punctuateModel === 'section') {
              this.seatPointList = [];
              if(this.points.length < 2) {
                this.$message.error('至少选择两个点')
                return;
              }
              // 从this.points中计算出座椅点
              var totalLength = 0;
              for(var i=1; i<this.points.length; i++) {
                var PA = this.points[i-1];
                var PB = this.points[i];
                totalLength += Math.sqrt((PA.x-PB.x)*(PA.x-PB.x) + (PA.y-PB.y)*(PA.y-PB.y))
              }
              var nameStart = parseInt(this.inputForm.nameStart);
              var nameEnd = parseInt(this.inputForm.nameEnd);
              console.log("totalLength:"+totalLength)
              console.log("nameStart:"+nameStart)
              console.log("nameEnd:"+nameEnd)
              var gap = nameEnd-nameStart;
              var gapDis = totalLength/(nameEnd-nameStart)
              console.log("gap:"+gap+"  "+gapDis)
            } else {
              this.submit();
            }
          }
        })
      },
      submit() {
        this.loading = true
        this.$http({
          url: `/smis/seat/jfSeatList/save`,
          method: 'post',
          data: this.inputForm
        }).then(({data}) => {
          if (data && data.success) {
            this.$refs.pointAddList.refreshList()
            this.$message.success(data.msg)
            this.resetFields()
          }
          this.loading = false
        })
      },
      // 更新当前所有数据的模型名称
      doUpdate() {
        if(!this.inputForm.floor.id || this.inputForm.floor.id === '') {
          return
        }
        this.loading = true
        this.$http({
          url: '/smis/seat/jfSeatList/list',
          method: 'get',
          params: {
            'pageNo': 1,
            'pageSize': 100000,
            'orderBy': '',
            'floor': {
              id: this.inputForm.floor.id
            }
          }
        }).then(({
          data
        }) => {
          if (data && data.success) {
            var dataList = data.page.list
            this.updateData(dataList)
          }
          this.loading = false
        })
      },
      updateData(dataList) {
        if (dataList.length === 0) {
          this.loading = false
          this.$message.success("处理完成")
          return
        }
        var item = dataList.shift();
        this.loading = true
        this.inputForm = item
        this.inputForm.meshName = this.$refs.pointAddList.findGroupName(item)
        this.$http({
          url: `/smis/seat/jfSeatList/save`,
          method: 'post',
          data: this.inputForm
        }).then(({
          data
        }) => {
          this.updateData(dataList);
          this.loading = false
        })
      },
      doDelete() {
        this.loading = true
        this.$http({
          url: '/smis/seat/jfSeatList/delete',
          method: 'delete',
          params: {
            'ids': this.selectItem.id
          }
        }).then(({
          data
        }) => {
          if (data && data.success) {
            this.$message.success(data.msg)
            this.$refs.pointAddList.refreshList()
            this.selectItem = {
              id: '',
              name: ''
            }
          }
          this.loading = false
        })
      },
      onMapClick(e) {
        var x = e.x;
        var y = e.y;
		var z = e.z;
        this.inputForm.x = x;
        this.inputForm.y = y;
        this.inputForm.z = z;
        if(this.punctuateModel === 'section') {
          this.points.push({x:x, y:y})
        }
        if (e.name.startsWith('jfdi') || e.name.startsWith('jflu') || e.name.startsWith('di') || e.name.startsWith(
          'lu')) {
          this.$message({
            message: '当前选中的点，不在模型上',
            type: 'warning'
          });
          this.inputForm.meshName = ''
        } else {
          this.inputForm.meshName = e.name
        }
      },
      clearPoints() {
        this.points = []
      },
      onDataClick(e) {
        this.selectItem = e
      },
      OnClose() {
        this.$emit('refreshDataList')
      }
    }
  }
</script>
<style scoped="scoped">
  .uni-foot {
    position: absolute;
    left: 0;
    width: 100%;
    bottom: 60px;
    text-align: right;
    padding: 0 10px;
    color: #096DD9;
  }

  .uni-foot .el-button--text {
    color: #096DD9;
    font-size: 12px;
  }
  .uni-popover-notice {
    font-size: 12px;

    span {
      color: #F5222D;
    }
  }
</style>
